package com.eptok.gw.szcups.cups.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ys8583.parse.IOMessage;

import com.eptok.gw.szcups.common.GateWayConstant;
import com.solab.iso8583.common.ByteUtil;


/**
 *@author:heqishan, Email:heqishan@gmail.com
 *2013-3-5 下午04:57:10
 */
public class Encoder extends ProtocolEncoderAdapter{
	
	private static final Logger log = LoggerFactory.getLogger(Encoder.class);
	
	private String encoderName;
	public Encoder(String encoderName){
		this.encoderName = encoderName;
	}

	public void encode(IoSession session, Object object, ProtocolEncoderOutput out)
			throws Exception {
		byte[] bodyBytes = null;
		if(object instanceof IOMessage){
			IOMessage iomessage = (IOMessage) object;
			bodyBytes = iomessage.toGetByte();
		}else{
			bodyBytes = (byte[])object;
			
		}
		int bodyLen = bodyBytes.length;
		String len = ByteUtil.fillString(String.valueOf(bodyLen), '0', 4, false);
		byte[] hexLenBytes = len.getBytes(GateWayConstant.CHAR_ENCODE);
		byte[] message = ByteUtil.byteAndByte(hexLenBytes, bodyBytes);
		if(bodyLen > 0){
			log.debug(encoderName + "发送完整数据:" + ByteUtil.BinaryToHexString(message));
		}
		IoBuffer buf = IoBuffer.allocate(message.length);
		buf.put(message);
		buf.flip();
		out.write(buf);
		buf.free();
		
	}
	
}
